#pragma once

#include <iostream>
#include <memory>
#include <cstdlib>
#include <string>
#include <strings.h>
#include <functional>
#include "Logger.hpp"
#include "Mutex.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

//回调函数
using callback_t = std::function<std::string \
    (const std::string &word, const std::string &whoip, uint16_t whoport)>;

const static int defaultsockfd = -1;

class DictSever
{
public:
    DictSever(uint16_t port, callback_t cb)
        :_sockfd(defaultsockfd),
         _port(port),
         _is_running(false),
         _cb(cb)
    {}
    //初始化
    void Init()
    {
        //1.创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "create socket error!";
            exit(1);
        }
        LOG(LogLevel::INFO) << "create socket success!" << _sockfd;
        //2.bind链接
        //2.1填充IP和port
        struct sockaddr_in local;
        bzero(&local, sizeof(local)); //清空数据
        local.sin_family = AF_INET;
        local.sin_port = htons(_port); //将端口号转为大端模式
        //这里绑定任意IP，也就是说不明确具体IP，只要发对应的主机号和port
        local.sin_addr.s_addr = htonl(INADDR_ANY);
        //inet_addr函数可以将字符串转为整数，且ip是网络序列的
        //2.2和socketfd链接
        int n = bind(_sockfd, (struct sockaddr*)&local, sizeof(local));
        if(n < 0)
        {
            LOG(LogLevel::FATAL) << "bind socket error!";
            exit(2);
        }
        LOG(LogLevel::INFO) << "bind socket success!";
    }
    //启动
    void Start()
    {
        _is_running = true;
        while(_is_running)
        {
            char buffer[1024];
            buffer[0] = 0; //清空数据
            struct sockaddr_in pere;
            socklen_t len = sizeof(pere);
            //读取数据
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer), 0, (struct sockaddr*)&pere, &len);
            if(n > 0)
            {   
                buffer[n] = 0;
                //获取对方ip和port
                uint16_t clintport = ntohs(pere.sin_port);
                std::string clintip = inet_ntoa(pere.sin_addr);
                //回调
                std::string word = buffer;
                LOG(LogLevel::INFO) << "Clint Sreach# " << word;
                std::string result = _cb(word, clintip, clintport);
                //发送数据
                sendto(_sockfd, result.c_str(), result.size(), 0,
                    (struct sockaddr*)&pere, len);
            }
        }
        _is_running = false;
    }
    //关闭
    void Stop()
    {
        _is_running = false;
    }
    ~DictSever()
    {}
private:
    int _sockfd;
    uint16_t _port;
    bool _is_running;
    callback_t _cb;
};